Alexgogoing

css基本功 position中的sticky

字数统计: 253阅读时长: 1 min
2021/06/02 Share

[css基本功] position的sticky(粘性布局)

众所周知,position的四个属性值为static、relative、absolute、fixed,在css3中新增了sticky,意为粘性布局

释义

position: sticky 结合了static和fixed两者特性,当页面元素满足固定距离时,使用类fixed定位方式(top、right、bottom、left生效);当未达到固定距离时,依照默认布局排列,top、right、bottom、left不生效。

Coding

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<style>
header > nav {
text-align: center;
}

.block-item{
height: 500px;
line-height: 500px;
background: #bbb;
text-align: center;
box-sizing: border-box; /* 包含border的盒子 */
border: 2px dashed #fff;
}

footer{
height: 50px;
line-height: 50px;
background: darkblue;
text-align: center;
position: sticky;
bottom: 0;
}

footer > p{
margin: 0;
padding: 0;
color: #fff;
}
</style>

<header>
<nav>
<a>I'm Header</a>
</nav>
</header>
<div class="block-item">占位</div>
<div class="block-item">占位</div>
<footer>
<p>I'm Footer</p>
</footer>

效果

当页面上下滚动时,header会固定在上方,footer会固定在下方。

CATALOG
  1. 1. [css基本功] position的sticky(粘性布局)
    1. 1.1. 释义
    2. 1.2. Coding
    3. 1.3. 效果